import React from 'react';
import { Layout, notification } from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import Media from 'react-media';
import Header from './Header';
import Context from './MenuContext';
import SiderMenu from '../components/SiderMenu';
import getPageTitle from '../utils/getPageTitle';
import { projectName, leftMenuWidth } from '../../config';
import tools from '../utils';
import '@ant-design/compatible/assets/index.css';
import './BasicLayout.less';

const { Content } = Layout;
const logo  = require('../assets/' + projectName + '/images/logo.png');
const logo2 = require('../assets/' + projectName + '/images/favicon.png');
let mapping = {};

// 把路由转换成菜单
function formatter(data, parentLocale) {
	const newData = [];

	for (let i = 0; i < data.length; i += 1) {
		const item = data[i];
		const { name, path, authority, routes, icon } = item;

		// 过滤
		if (!name || !path) continue;
		if (authority && !authority.length) continue;

		let locale = parentLocale ? parentLocale + '.' : 'menu.';
		locale += name;

		const newItem = {
			name,
			path,
			locale,
		};

		// 下级菜单
		const children = routes && routes.length ? formatter(routes, locale) : [];
		if (children.length) newItem.children = children;
		if (icon) newItem.icon = icon;

		newData.push(newItem);
	}

	return newData;
}

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

class BasicLayout extends React.Component {
	state = {
		menuData: [], // 可见菜单数据
	};

  constructor(props) {
    super(props);

    const ua = window.navigator.userAgent;
    // 一次定义，方便随处使用
    window.isIE = ua.indexOf("Windows NT") > 0 && ua.indexOf("Trident") > 0;
    if (window.isIE) {
      notification.info({
        message: "系统提示",
        description: '您正在使用过时的IE浏览器，为了保证您能够正常使用本系统，我们推荐您使用谷歌浏览器，或者切换到"极速模式"。',
        duration: null, // 不自动关闭
      });
    }

		const {
			dispatch,
			route: { routes, path, authority },
		} = this.props;

		// 依据后台接口返回的菜单数据，生成可见导航菜单
		const menuStr = tools.funcGetLocalValue('menuData') || '[]';
		const menus = JSON.parse(menuStr);
		mapping = {};

		for (let i = 0; i < menus.length; i += 1) {
			const item = menus[i];
			const { name, page } = item;
			const key = name + '_' + page;
			mapping[key] = item;
		}

		this.funcAddAuth(routes);
		let { state } = this;
		state.menuData = formatter(routes);

		// 依据后台接口返回的资源数据，生成可用资源
		const resStr = tools.funcGetLocalValue('resStr');
		const resData = resStr.split(',');

		dispatch({
			type: 'setting/getSetting',
		});
		dispatch({
			type: 'menu/update',
			payload: { routes, path, authority, resData },
		});
  }

	// 设置可见菜单(给路由数组附上"authority"属性)
	funcAddAuth(arr) {
		const {
			route: { authority },
		} = this.props;

		for (let i = 0; i < arr.length; i += 1) {
			const item = arr[i];
			const { name, path, routes } = item;

			if (!name || !path) continue;
			if (name.indexOf('首页') >= 0) continue;

			const pathData = path.split('/');
			const page = pathData[pathData.length - 1];
			const key = name + '_' + page;

			item.authority = mapping[key] ? authority : [];

			if (routes && routes.length) this.funcAddAuth(routes);
		}
	}

  getContext() {
    const { location, breadcrumbNameMap } = this.props;
    return {
      location,
      breadcrumbNameMap,
    };
  }

  getLayoutStyle = () => {
    const { fixSiderbar, isMobile, collapsed, layout } = this.props;
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
      return {
        paddingLeft: collapsed ? '80px' : leftMenuWidth + 'px',
      };
    }
    return null;
  };

  // 布局的样式
  getContentStyle = () => {
    const { fixedHeader, isMobile } = this.props;
    return {
      margin: isMobile ? '16px 8px 0 8px' : '24px 24px 0 24px',
      paddingTop: fixedHeader ? 64 : 0,
    };
  };

  // 左侧导航菜单的显隐事件
  handleMenuCollapse = collapsed => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };

  render() {
		const { menuData } = this.state;
    const {
      navTheme,
      layout: PropsLayout,
      children,
      location: { pathname },
      isMobile,
      collapsed,
      breadcrumbNameMap,
    } = this.props;

    const isTop = PropsLayout === 'topmenu';

    const layout = (
      <Layout>
        {isTop && !isMobile ? null : (
          <SiderMenu
            logo={isMobile && collapsed ? logo2 : logo}
            theme={navTheme}
            onCollapse={this.handleMenuCollapse}
            menuData={menuData}
            isMobile={isMobile}
            {...this.props}
          />
        )}
        <Layout style={{ ...this.getLayoutStyle() }}>
          <Header
            menuData={menuData}
            handleMenuCollapse={this.handleMenuCollapse}
            logo={isMobile && collapsed ? logo2 : logo}
            isMobile={isMobile}
            {...this.props}
          />
          <Content style={this.getContentStyle()}>{children}</Content>
        </Layout>
      </Layout>
    );

    return (
      <React.Fragment>
        <DocumentTitle title={getPageTitle(pathname, breadcrumbNameMap)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider value={this.getContext()}>
                <div className={classNames(params)}>{layout}</div>
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
      </React.Fragment>
    );
  }
}

export default connect(({ global, setting, menu }) => ({
  collapsed: global.collapsed,
  layout: setting.layout,
  breadcrumbNameMap: menu.breadcrumbNameMap,
  ...setting,
}))(props => (
  <Media query="(max-width: 576px)">
    {isMobile => (
			<Media query="(max-width: 768px)">
				{isPad => {
          window.isMobile = isMobile;
					window.isPad = isMobile ? false : isPad; // 不能既是平板又是手机
					return <BasicLayout {...props} isMobile={isMobile} />;
				}}
			</Media>
		)}
  </Media>
));
